package com.example.product.controller;

import cn.hutool.crypto.SecureUtil;
import com.example.product.entity.Account;
import com.example.product.entity.Admin;
import com.example.product.entity.User;
import com.example.product.service.AdminService;
import com.example.product.service.UserService;
import com.example.product.util.Result;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;


@RestController
public class WebController implements WebMvcConfigurer {
    @Value("${upload.filePath}")
    private String uploadPath;

    @Value("${upload.handler}")
    private String handler;

    @Resource
    AdminService adminService;

    @Resource
    UserService userService;

    /**
     * 默认请求接口
     */
    @GetMapping("/")
    public Result hello() {
        return Result.success();
    }

    /**
     * 登录
     */
    @PostMapping("/login")
    @ApiOperation("登录接口")
    public Result login(@RequestBody Account account) {
        Result ac = null;
        if ("ADMIN".equals(account.getRole())) {
            ac = adminService.login(account);
        } else {
            ac = userService.login(account);
        }
        return Result.success(ac);
    }

    /**
     * 注册
     */
    @PostMapping("/register")
    @ApiOperation("注册接口")
    public Result register(@RequestBody User user) {
        userService.register(user);
        return Result.success();
    }

    /**
     * 修改密码
     */
    @PutMapping("/updatePassword")
    @ApiOperation("修改密码接口")
    public Result updatePassword(@RequestBody Account account) {
        System.out.println("密码: " + account.getNewPassword());
        // 加密新密码
        String encryptedPassword = SecureUtil.md5(account.getNewPassword());
        System.out.println("密码: "+ encryptedPassword);
        // 创建一个新的 Account 对象，保存加密后的密码
        Account updatedAccount = new Account();
        updatedAccount.setUsername(account.getUsername());
        updatedAccount.setPassword(encryptedPassword);
        updatedAccount.setRole(account.getRole());
        // ec6a6536ca304edf844d1d248a4f08dc

        // 根据角色调用相应的服务更新密码
        if ("ADMIN".equals(updatedAccount.getRole())) {
            adminService.updatePassword(updatedAccount);
        } else {
            userService.updatePassword(updatedAccount);
        }
        return Result.success();
    }


}
